var baseUrl=`http://localhost:8000`

$(function(){

    $.get(`${baseUrl}/blog`,data=>{
        console.log(data);
        render(data)
    })


})


function render(data){
     $('.tr').remove()

    data.forEach((item,index) => {
        if(index%2==0){
            let html=`
            <tr class="tr" style="background-color: burlywood">
               <td>${item.id}</td>
               <td>${item.biaoti}</td>
               <td>${item.zhaiyao}</td>
               <td>${item.neirong}</td>
               <td>${item.fenlei}</td>
               <td>${item.zuozhe}</td>
               <td>
                   <input type="button" value="编辑" onclick="update_btn(${item.id})">
                   <input type="button" value="删除" onclick="delete_btn(${item.id})">
               </td>
            </tr>
            `
            $('#tb').append(html)
        }else{
            let html=`
            <tr class="tr" style="background-color: cornflowerblue">
               <td>${item.id}</td>
               <td>${item.biaoti}</td>
               <td>${item.zhaiyao}</td>
               <td>${item.neirong}</td>
               <td>${item.fenlei}</td>
               <td>${item.zuozhe}</td>
               <td>
                   <input type="button" value="编辑" onclick="update_btn(${item.id})">
                   <input type="button" value="删除" onclick="delete_btn(${item.id})">
               </td>
            </tr>
            `
            $('#tb').append(html)
        }

    });
}


function select_btn(){
    let keyword=$('[name=keyword]').val()
    
    
        $.get(`${baseUrl}/blog?keyword=`+keyword,data=>{
            console.log(data);
            render(data)
        })
    



}

function delete_btn(id){
    if(confirm('确认删除吗？')){
        $.ajax({
            type:'delete',
            url:`${baseUrl}/blog/${id}`,
            success:function(res){
                console.log(res);
                render(res)
            }
        })
    }


}

function add_btn(){
    window.location.href='./addOrEdit.html';
}

function save_btn(){
    let biaoti=$('[name=biaoti]').val();
    let zhaiyao=$('[name=zhaiyao]').val();
    let neirong=$('[name=neirong]').val();
    let fenlei=$('[name=fenlei]').val();
    let zuozhe=$('[name=zuozhe]').val();

    let id=window.location.search.split('?')[1];
    let obj={
        biaoti,zhaiyao,neirong,fenlei,zuozhe
    }
    
    if(id){
        $.ajax({
            type:'put',
            url:`${baseUrl}/blog/${id}`,
            data:obj,
            success:function(res){
                console.log(res);
            render(res)
            window.location.href='./index.html'
            }
        })
    }else{
        $.post(`${baseUrl}/blog`,obj,data=>{
            render(data)
            window.location.href='./index.html'
        })
    }



}


function update_btn(id){
    window.location.href=`./addOrEdit.html?${id}`
}

function cansel_btn(){
    window.location.href=`./index.html`

}